package com.example.environment;

import liquibase.exception.LiquibaseException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangbin
 */
@RestController
public class EnvironmentController {
    @Resource
    private EnvironmentService environmentService;
    @Resource
    private EnvironmentRepository environmentRepository;

    /**
     * 获取环境列表
     *
     * @return 环境列表
     */
    @GetMapping("/api/environment")
    public List<Environment> list() {
        return environmentRepository.findAllFetch();
    }

    /**
     * 获取环境详情
     *
     * @param id 环境id
     * @return 环境详情
     */
    @GetMapping("/api/environment/{id}")
    public Environment getOne(@PathVariable Long id) {
        return environmentRepository.findById(id).orElseThrow(RuntimeException::new);
    }

    /**
     * 保存环境详情
     *
     * @param environment 环境详情
     */
    @PostMapping("/api/environment")
    public void save(@RequestBody Environment environment) {
        environmentRepository.save(environment);
    }

    /**
     * 对比
     *
     * @param envId   环境id
     * @param tableId 表id
     * @return 对比sql
     * @throws LiquibaseException           LiquibaseException
     * @throws ParserConfigurationException ParserConfigurationException
     * @throws IOException                  IOException
     */
    @GetMapping("/api/environment/diff/{envId}/{tableId}")
    public Map<String, Object> diff(@PathVariable Long envId, @PathVariable Long tableId) throws LiquibaseException, ParserConfigurationException, IOException {
        String sql = environmentService.diff(envId, tableId);
        Map<String, Object> result = new HashMap<>(0);
        result.put("data", sql);
        return result;
    }

    /**
     * 同步数据库
     *
     * @param envId   环境id
     * @param tableId 表id
     * @throws LiquibaseException           LiquibaseException
     * @throws ParserConfigurationException ParserConfigurationException
     */
    @GetMapping("/api/environment/update/{envId}/{tableId}")
    public void update(@PathVariable Long envId, @PathVariable Long tableId) throws LiquibaseException, ParserConfigurationException, IOException {
        environmentService.update(envId, tableId);
    }

}
